package com.example.config;

import com.example.service.HttpClient;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixObservableCommand;
import rx.Observable;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

public class UserHystrixCommand extends HystrixObservableCommand<Map<String,Object>> {

    private Supplier<Observable<Map<String,Object>>> suplier;

    public UserHystrixCommand(Supplier<Observable<Map<String,Object>>> suplier,int executionTimeoutInMilliseconds,int executionIsolationSemaphoreMaxConcurrentRequests) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("hello-group"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("/threadtest"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(executionTimeoutInMilliseconds)
                                                                                .withExecutionIsolationSemaphoreMaxConcurrentRequests(executionIsolationSemaphoreMaxConcurrentRequests)
                ));
        this.suplier=suplier;
    }

    @Override
    protected Observable<Map<String, Object>> construct() {
        Observable<Map<String,Object>> response=suplier.get();
        return response;
    }

    @Override
    protected Observable<Map<String, Object>> resumeWithFallback() {
        Map<String,Object> ret=new HashMap<>();
        ret.put("message","hystrix blocked!");
        ret.put("downstream-resp-status",500);
        return Observable.just(ret);
    }
}
